package nancal.mp.mvc.admin

import io.swagger.annotations.Api
import nbcp.base.comm.ApiResult
import nbcp.base.model.SshClient
import nbcp.base.utils.CodeUtil
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File

@Api(description = "Ssh", tags = arrayOf("Ssh"))
@RestController
@RequestMapping("/ssh")
class SshController {
    companion object {
        val connected = mutableMapOf<String, SshClient>()
    }

//    class Ssh{
//        var host:String = ""
//        var port:Int = 0
//        var user:String = ""
//        var password:String = ""
//    }

    @PostMapping("/open")
    fun open(host: String, user: String, password: String): ApiResult<String> {
        var ssh = SshClient();
        ssh.host = host;
        ssh.userName = user;
        ssh.password = password;


        var id = CodeUtil.getCode();
        connected[id] = ssh;

        return ApiResult.of(id);
    }

    @GetMapping("/test")
    fun test(id: String): ApiResult<Boolean> {
        if (!connected.containsKey(id)) {
            return ApiResult.of(false)
        }

        if (connected[id]!!.isConnected()) {
            return ApiResult.of(true)
        }

        connected.remove(id);
        return ApiResult.of(false);
    }

    @PostMapping("/exec/{id}")
    fun exec(id: String, cmd: String): ApiResult<String> {
        var res = test(id);
        if (res.data != true) {
            return ApiResult.of("连接已丢失");
        }

        return connected[id]!!.exec( cmd);
    }


    @PostMapping("/test-scp")
    fun testScp(id: String): ApiResult<String> {
        var res = test(id);
        if (res.data != true) {
            return ApiResult.of("连接已丢失");
        }

        return connected[id]!!.scp( File("/app/test-src"), "/test/test-target");
    }
}